package com.tianji.learning.mq;
import cn.hutool.core.util.ObjectUtil;
import com.tianji.api.dto.trade.OrderBasicDTO;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.utils.CollUtils;
import com.tianji.learning.service.ILearningLessonService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

//课程监听器
@Component
@Slf4j
@RequiredArgsConstructor
public class LessonChangeListener {

    private final ILearningLessonService lessonService;

    /**
     * 监听-订单支付或课程报名的消息
     * 添加课程到课表
     * @param order 订单信息
     */
    @RabbitListener(bindings = @QueueBinding(
            //课程支付
            value = @Queue(value = "learning.lesson.pay.queue", durable = "true"),
            //订单有关的交换机
            exchange = @Exchange(name = MqConstants.Exchange.ORDER_EXCHANGE, type = ExchangeTypes.TOPIC),
            //订单交易有关的RoutingKey
            key = MqConstants.Key.ORDER_PAY_KEY
    ))
    private void listenLessonPay(OrderBasicDTO order){
        log.info("接收到下单购买课程消息，消息体{}",order);

        //1.健壮性处理
        //ObjectUtil.isEmpty(order);
        if (order == null || order.getUserId() == null || CollUtils.isEmpty(order.getCourseIds())) {
            //数据有误，无需处理
            log.error("接收到的MQ消息有误，订单数据为空");
            return;
        }

        //2.数据正常，则添加课程到课程表
        log.info("监听到用户{}的订单{}，需要添加课程{}到课表中", order.getUserId(), order.getOrderId(), order.getCourseIds());
        lessonService.addUserLessons(order.getUserId(),order.getCourseIds());
    }


    //监听-退款-移除课表中的课程
}
